#include "mainwindow.h"
#include "workthread.h"
#include <QVBoxLayout>
#include <QLCDNumber>
#include <QPushButton>
#include <QTimer>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    QWidget *widget = new QWidget(this);
    QVBoxLayout *layout= new QVBoxLayout;
    widget->setLayout(layout);

    QLCDNumber *lcdNumber = new QLCDNumber(this);
    layout->addWidget(lcdNumber);
    QPushButton *button = new QPushButton(tr("Start"), this);
    layout->addWidget(button);
    setCentralWidget(widget);

    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, [=](){
        static int sec = 0;
        lcdNumber->display(QString::number(++sec));
    });

    WorkThread *thread = new WorkThread(this);
    connect(thread, &WorkThread::done, timer, &QTimer::stop);
    // thread任务完成时，使用 deleteLater清除线程实例
    connect(thread, &WorkThread::finished, thread, &WorkThread::deleteLater);
    connect(button, &QPushButton::clicked, [=](){
        timer->start(1);
        // 如果有耗时的操作， 应该从主线程(UI线程)中分离出来，使用多线程
        // 避免UI失去响应
        //  for (long i = 0; i < 2000000000; ++i); // incompetence, should start another thread.

        // 使用thread会创建一个线程
        thread->start();
    });
}

MainWindow::~MainWindow()
{

}

